// store.js
import { createStore } from 'vuex';

const initialState = () => {
    const validRoles = ['admin', 'client'];
    const storedRole = localStorage.getItem('userRole');
    return {
        isLogin: !!localStorage.getItem('satoken'),
        token: localStorage.getItem('satoken') || '',
        isClient: validRoles.includes(storedRole) && storedRole === 'client',
        isAdmin: validRoles.includes(storedRole) && storedRole === 'admin'
    };
};

export default createStore({
    state: initialState,

    mutations: {
        setClientRole(state) {
            state.isClient = true;
            state.isAdmin = false;
            localStorage.setItem('userRole', 'client');
        },
        setAdminRole(state) {
            state.isAdmin = true;
            state.isClient = false;
            localStorage.setItem('userRole', 'admin');
        },
        setToken(state, token) {
            state.token = token;
            localStorage.setItem('satoken', token);
            state.isLogin = !!token;
        },
        clearToken(state) {
            state.token = '';
            state.isClient = false;
            state.isAdmin = false;
            state.isLogin = false;
            localStorage.removeItem('satoken');
            localStorage.removeItem('userRole');
        }
    },

    actions: {
        async loginSuccess({ commit }, { token, role }) {
            try {
                commit('setToken', token);
                if (role === 'admin') {  // 假设后端返回英文角色
                    commit('setAdminRole');
                } else if (role === 'client') {
                    commit('setClientRole');
                } else {
                    console.error("Invalid role");
                }
            } catch (error) {
                console.error('Login failed:', error);
                commit('clearToken');
            }
        },
        logout({ commit }) {
            commit('clearToken');
        }
    },

    getters: {
        isAuthenticated: state => state.isLogin,
        authToken: state => state.token,
        isClient: state => state.isClient,
        isAdmin: state => state.isAdmin
    }
});

// 判断内容是否含有表情字符，现有数据库不支持。
export function hasEmoji (str = '') {
    const reg = /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g;
    return str.match(reg) && str.match(reg).length
}

// 单张图片上传
export const uploadImgServer = '/api/common/file/upload'
// 多张图片上传
export const uploadImgsServer = 'http://backend-api-02.newbee.ltd/manage-api/v1/upload/files'
